function AppController(){
	this.rooms=[];
	this.user=null;
	this.currentRoom=null;
	this.users=[];
}

AppController.prototype.init = function(session){
	this.rooms.push(new Room(session));
	this.user=new User();
	this.currentRoom=this.rooms[0];
};

function listenerAdd(overlay){
	var o=$("#blogId").val();
	if($("#add-form").hasClass("ui-panel-open") && 
			  (o=='circle' || o=='rectangle' || o=='polyline' || o=='polygon' || o=='marker'))
		return;
	$("#blogId").val(overlay);
	$("#rating").hide();
	$('#title').val('');
	$("#title").prop('disabled', false);
	$('#description').val('');
	$("#description").prop('disabled', false);
	$("#publishTime").html('');
	$("#listFiles").html('');
	$("#mediaButton").show();
	$("#mediaThumbnail").hide();
	$("#socialButton").hide();
	$("#actionButton").show();
	$("#comments").hide();
	app.currentRoom.infowindow.close();
	if($("#add-form").hasClass("ui-panel-open"))
		return;
	$("#panelD").click();	
}

function loadBlog(blogId){
	for(var j=0;j<app.currentRoom.publicBlogs.length;j++){
		if(app.currentRoom.publicBlogs[j].id==blogId){
			return app.currentRoom.publicBlogs[j];			
		}				
	}
}

function loadImage(files){
	$("#thumbnail").html('');
	for(var i=0;i<files.length;i++){
		$("#thumbnail").html($("#thumbnail").html()+
				"<div>"+
				  "<a class='fancybox' rel='group' href='"+files[i]+"' style='width: 50px; height: 50px;'>"+
				    "<img class='media-object img-thumbnail' style='width: 50px; height: 50px;' src='"+files[i]+"'></a>"+
				"</div>");
	}
}
function getDivPreview(comment){
	if(comment.length>=40){
		var preview=comment.substring(0,40);
		var rest=comment.substring(40);
		var result="<div class='ui-body ui-body-a wrap strech' style='font-size:0.9em;'>"+
		preview+"<a class='readmorebtn'>...[+]</a>"+
		"<p class='more'>"+rest+"</p>"+
		"</div>";
		return result;
	}else{
		var result="<div class='ui-body ui-body-a strech' style='font-size:0.9em;'>"+				
		"<p>"+comment+"</p>"+
		"</div>";
		return result;
	}
}

function loadComment(blog){
	$('#listComments').html('');
	for(var k=blog.comments.length-1;k>=0;k--){
		var div=getDivPreview(blog.comments[k].body);
		$('#listComments').html($('#listComments').html()+
			"<div class='ui-corner-all custom-corners'>"+
			"<div class='ui-bar ui-bar-a strech' style='font-size:0.8em;'>"+
			"<h3>"+blog.comments[k].userId+" at "+blog.comments[k].time+"</h3>"+
			"</div>"+
			div+				
			"<a href='#' class='ui-btn ui-icon-comment ui-btn-icon-right ui-btn-icon-notext ui-shadow ui-corner-all response'></a>"+
			"<input class='commentIdRef' value='"+blog.comments[k].id+"' type='hidden'>"+
			"<input class='level' value='"+blog.comments[k].level+"' type='hidden'>"+
		"</div>");
		var commentList=blog.comments[k].commentList;
		for(var i=0;i<commentList.length;i++){
			var div2=getDivPreview(commentList[i].body);
			$('#listComments').html($('#listComments').html()+
				"<div class='ui-corner-all custom-corners' style='margin-left:"+commentList[i].level*10+"%;'>"+
				"<div class='ui-bar ui-bar-a strech' style='font-size:0.8em;'>"+
				"<h3>"+commentList[i].userId+" at "+commentList[i].time+"</h3>"+
				"</div>"+
				div2+				
				"<a href='#' class='ui-btn ui-icon-comment ui-btn-icon-right ui-btn-icon-notext ui-shadow ui-corner-all response'></a>"+
				"<input class='commentIdRef' value='"+commentList[i].id+"' type='hidden'>"+
				"<input class='level' value='"+commentList[i].level+"' type='hidden'>"+
			"</div>");
		}
	}	
}
function listenerPublish(blogId,title,description,files,time){
	var blog=loadBlog(blogId);
	$("#blogId").val(blogId);
	$("#title").val(title);
	$("#title").prop('disabled', true);
	$("#description").val(description);
	$("#description").prop('disabled', true);
	$("#publishTime").html("Publish at "+time+" by "+blog.userId);
	$("#comment").val("");
	$("#rating").show();
	var avg=parseInt(blog.average());
	var detail=blog.detailRating();	
	$('input[name=star2]').rating('readOnly',false);
	if(avg==0)
		$(".rating-cancel").click();
	else
		$('input[name=star2]').rating('select',avg-1);	
	$('input[name=star2]').rating('readOnly',true);	
	$("#d1").html(detail[0]);
	$("#d2").html(detail[1]);
	$("#d3").html(detail[2]);
	$("#d4").html(detail[3]);
	$("#d5").html(detail[4]);
	$("#d6").html(detail[5]);
	$("#d7").html(detail[6]);
	loadImage(files);
	loadComment(blog);
	var score=blog.rateHashMap.get($("#userName").val());
	$('input[name=star1]').rating('readOnly',false);
	if(score!=null){	
		$('input[name=star1]').rating('select',score-1);
		$('input[name=star1]').rating('readOnly',true);	
		$("#rate").hide();
		$("#rating").show();
	}else{
		$(".rating-cancel").click();
		$("#rate").show();
		$("#rating").hide();
	}	
	$("#mediaButton").hide();
	$("#mediaThumbnail").show();
	$("#socialButton").show();
	$("#likes").val(blog.likes);
	$("#dislikes").val(blog.dislikes);
	$("#actionButton").hide();
	$("#comments").show();
	var visitor=blog.isVisitor($("#userName").val());
	if(visitor==undefined)
		app.currentRoom.visit(blog.id,$("#userName").val());
	if($("#add-form").hasClass("ui-panel-open"))
		return;
	$("#panelD").click();	
}
function resetField(){
	$('#title').val('');
	$('#description').val('');
	$("#listFiles").html('');
}

function rateBlog(blogId,userName,score){
	var blog=loadBlog(blogId);
	var map=blog.rateHashMap;
	map.put(userName,score);
	if($("#userName").val()==userName){
		$('input[name=star1]').rating('readOnly',true);
		$("#rate").hide();
		$("#rating").show();
	}
	var avg=parseInt(blog.average());
	if($("#add-form").hasClass("ui-panel-open") && $("#blogId").val()==blogId){		
		$('input[name=star2]').rating('readOnly',false);
		$('input[name=star2]').rating('select',avg-1);
		$('input[name=star2]').rating('readOnly',true);	
		var detail=blog.detailRating();	
		$("#d1").html(detail[0]);
		$("#d2").html(detail[1]);
		$("#d3").html(detail[2]);
		$("#d4").html(detail[3]);
		$("#d5").html(detail[4]);
		$("#d6").html(detail[5]);
		$("#d7").html(detail[6]);
	}
	if(blog.type=='marker'){
		if(avg<4)
			blog.overlay.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
		else if(avg>=4)
			blog.overlay.setIcon("http://maps.google.com/mapfiles/ms/icons/green-dot.png");
	}
	else{
		if(avg<4)
			blog.overlay.setOptions({strokeColor: "#B40404"});
		else if(avg>=4)
			blog.overlay.setOptions({strokeColor: "#48C921"});
	}	
}

function addLikeByBlogId(blogId){
	var blog=loadBlog(blogId);
	blog.likes++;
	if($("#add-form").hasClass("ui-panel-open") && $("#blogId").val()==blogId){
		$("#likes").val(blog.likes);
		$("#score").html("Score: "+(blog.likes-blog.dislikes));
	}
}
function addDislikeByBlogId(blogId){
	var blog=loadBlog(blogId);
	blog.dislikes++;
	if($("#add-form").hasClass("ui-panel-open") && $("#blogId").val()==blogId){
		$("#dislikes").val(blog.dislikes);
		$("#score").html("Score: "+(blog.likes-blog.dislikes));
	}
}

function addOneComment(id,blogId,userName,body,time){
	if($("#add-form").hasClass("ui-panel-open") && $("#blogId").val()==blogId){
		var div=getDivPreview(body);
		$('#listComments').html("<div class='ui-corner-all custom-corners'>"+
				"<div class='ui-bar ui-bar-a strech' style='font-size:0.8em;'>"+
				"<h3>"+userName+" at "+time+"</h3>"+
				"</div>"+
				div+
				"<a href='#' class='ui-btn ui-icon-comment ui-btn-icon-right ui-btn-icon-notext ui-shadow ui-corner-all response'></a>"+
				"<input class='commentIdRef' value='"+id+"' type='hidden'>"+
				"<input class='level' value='0' type='hidden'>"+
				"</div>"+
				$('#listComments').html());		
	}
}
function addOneSubComment(id,blogId,userName,body,time,commentIdRef,level){
	if($("#add-form").hasClass("ui-panel-open") && $("#blogId").val()==blogId){
		var lastParent=$("[value="+commentIdRef+"]").parent();
		var div2=getDivPreview(body);
		lastParent.html(lastParent.html()+
				"<div class='ui-corner-all custom-corners'style='margin-left:"+level*10+"%;'>"+
				"<div class='ui-bar ui-bar-a strech' style='font-size:0.8em;'>"+
				"<h3>"+userName+" at "+time+"</h3>"+
				"</div>"+
				div2+				
				"<a href='#' class='ui-btn ui-icon-comment ui-btn-icon-right ui-btn-icon-notext ui-shadow ui-corner-all response'></a>"+
				"<input class='commentIdRef' value='"+id+"' type='hidden'>"+
				"<input class='level' value='"+level+"' type='hidden'>"+
			"</div>");		
	}
}
function setOtherPosition(userName,lat,lng){
	var pos = new google.maps.LatLng(lat,lng);
	var marker=new google.maps.Marker({
        clickable: true,
        position: pos,
        icon: 'resources/images/group-2.png',
        shadow: null,
        zIndex: 999,
        map: app.currentRoom.map 
    });
	var infowindow = new google.maps.InfoWindow({
	    content: userName
	});
	google.maps.event.addListener(marker, 'click', function() {
		  infowindow.open(app.currentRoom.map,marker);
	});
	var n=app.users.length;
	var user=new User();
	user.myLocation=marker;
	user.name=userName;
	app.users[n]=user;	
}
function changeOtherPosition(user,lat,lng){
	var pos = new google.maps.LatLng(lat,lng);
	user.myLocation.setPosition(pos);
}
function getTime(){
	var date=new Date();
	return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+
	" "+date.getDate()+"/"+(date.getMonth()+1)+"/"+date.getFullYear();	
}
function createMatchingList(matchingBlogs){
	$("#matchingList").hide();
	$("#resultList").html('Results');
	for(var i=0;i<matchingBlogs.length;i++){		
		$("#resultList").html($("#resultList").html()+"<button id='buttonList' type='button' class='ui-btn ui-btn-b ui-corner-all ui-mini' value="+matchingBlogs[i].id+">"+matchingBlogs[i].title+"</button>");
	}
}
function createMyMatchingList(matchingBlogs){
	$("#resultList").hide();
	$("#matchingList").html('');
	for(var i=0;i<matchingBlogs.length;i++){		
		$("#matchingList").html($("#matchingList").html()+"<button id='buttonList' type='button' class='ui-btn ui-btn-b ui-corner-all ui-mini' value="+matchingBlogs[i].id+">"+matchingBlogs[i].title+"</button>");
	}
}
function loadTableResume(){
	$("#tableResume").dataTable().fnDestroy();
	$("#tableResume tbody tr").remove();
	var blogs=app.currentRoom.publicBlogs;
	for(var i=0;i<blogs.length;i++){
		var avg=blogs[i].average();
		 $("#tableResume tbody").append(
				 "<tr>"+
			      "<td style='text-align:center;'><button id='buttonList' class='button-link' value="+blogs[i].id+">"+blogs[i].title+" ("+blogs[i].userId+")"+"</button></td>"+
			      "<td style='text-align:center;'>"+avg+"</td>"+			     
			      getIconTableResume(blogs[i].isVisitor($("#userName").val()))+
			      getIconTableResume(blogs[i].rateHashMap.get($("#userName").val()))+
			    "</tr>"	 
		 );
	}
	var oTable=$("#tableResume").dataTable({
	    "bPaginate": false,
	    "bFilter": false,
	    "bInfo": false,
	    "aoColumnDefs": [
	                     { "bSortable": false, "aTargets": [ 0,2,3 ] }
	                   ] 
	});
	oTable.fnSort( [ [1,'desc'] ] );
}
function getIconTableResume(value){	 
	 if(value!=undefined){
		 return  "<td style='text-align:center;'><button class='ui-btn ui-shadow ui-corner-all ui-icon-check ui-btn-icon-notext ui-mini button-table ui-btn-b' disabled></button></td>";
	 }else{
		 return  "<td style='text-align:center;'><button class='ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-notext ui-mini button-table ui-btn-b' disabled></button></td>";
	 }
	
}